package netty.netty5;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import netty.netty4.DiscardServerHandler;
import netty.netty4.TimeServerHandler;

/**
 * Created by IntelliJ IDEA.
 * User: liuliwei
 * Date: 2017-06-01
 * Time: 下午5:15
 * Description:
 */
public class DiscardServer {
    private  int port;

    public DiscardServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup= new NioEventLoopGroup();
        EventLoopGroup workGroup= new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new DiscardServerHandler());
                    ch.pipeline().addLast(new TimeServerHandler());
                }
            }).option(ChannelOption.SO_BACKLOG,128)
            .childOption(ChannelOption.SO_KEEPALIVE,true);

            //Bind and start to accept incoming connections
            ChannelFuture f = b.bind(port).sync();

            //wait until the server socket is closed
            // in this example ,this does not happen,but you can do this gracefully
            //shut down you server

            f.channel().closeFuture().sync();
        }finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
//
    // test server start
    // telnet localhost 8080
    public static void main(String[] args) throws Exception {
        int port;
        if (args.length>0) {
            port = Integer.valueOf(args[0]);
        }else {
            port = 8080;
        }
        new DiscardServer(port).run();

    }
}
